<template>
  <!--自定义分页表格-->
  <div class="table-page">
    <!-- 操作按钮栏目-->
    <slot name="operate-btn-bar" />
    <el-table
      ref="tablePagination"
      v-loading="loading"
      style="width:100%;"
      element-loading-background="rgba(0, 0, 0, 0.25)"
      element-loading-text="拼命加载中"
      :max-height="tableHeight"
      :show-summary="showSummary"
      :header-cell-class-name="addOne"
      :data="data"
      v-bind="$attrs"
      v-on="$listeners"
    >
      <!-- 当type:selection开启属性，出现选择框 -->
      <el-table-column v-if="selectionShow" type="selection" width="50" />
      <template v-if="isMultiCol">
        <business-multi-level-colums
          v-for="(col, key) in columns"
          :key="`col_${key}`"
          :col="col"
        />
      </template>
      <template v-else>
        <template v-for="(column, index) in columns">
          <!--作用域具名插槽列表头-->
          <el-table-column
            v-if="column.slot"
            :key="`col_${index}`"
            :prop="dropCol[index].prop"
            :label="column.label"
            :width="column.width || 'auto'"
            :min-width="column.minWidth || 'auto'"
            :fixed="column.fixed"
            :render-header="renderHeader"
            :align="column.align || 'center'"
          >
            <!--父类插槽作用域用法示例：-->
            <!--
            <el-table ...>
              <template slot="xx" slot-scope="scope">
                <button @click="eventName(scope.item)"></button>
              </template>
            </el-table>
          -->
            <template slot-scope="scope" :prop="dropCol[index].prop">
              <slot
                :name="dropCol[index].prop"
                :item="scope.row"
                :$index="scope.$index"
              />
            </template>
          </el-table-column>
          <!-- 普通列表头 -->
          <el-table-column
            v-else
            :key="column.key"
            :prop="dropCol[index].prop"
            :label="column.label"
            :width="column.width || 'auto'"
            :min-width="column.minWidth || 'auto'"
            :show-overflow-tooltip="isEllipsis(column.prop)"
            :formatter="column.formatter"
            :render-header="renderHeader"
            :align="column.align || 'center'"
          />
        </template>
      </template>
      <template slot="empty">
        <div v-show="!loading" class="empty-text">
          <svg-icon icon-class="taken" class="svg-container" />
          <span class="empty-content">{{ emptyText }}</span>
        </div>
      </template>
    </el-table>
    <!-- 分页选择器 -->
    <div v-if="paginationShow" ref="table-pagination" class="pagination">
      <el-pagination
        :current-page.sync="tableCurrentPage"
        :page-size.sync="tablePageSize"
        :pager-count="pagerCount"
        :page-sizes="pageSizes"
        :layout="layout"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>
<script>
import { mapActions } from 'vuex';
import promptMessage from '@/components/business/MultiLevelColums/promptMessage';
import BusinessMultiLevelColums from '@/components/business/MultiLevelColums';
import Sortable from 'sortablejs';

export default {
  name: 'TablePagination',
  components: {
    BusinessMultiLevelColums
  }, // 分页表格
  props: {
    needDrag: {
      type: Boolean,
      default: false
    },
    emptyText: { type: String, default: '暂无数据' },
    data: { default: () => [], type: Array, required: true }, // 数据项
    columns: { default: () => [], type: Array, required: true }, // 列表项
    selectionShow: { default: false, type: Boolean }, // 是否需要选择项
    overflowProp: { default: () => [], type: Array }, // 过长数据隐藏的属性
    paginationShow: { default: true, type: Boolean }, // 是否需要分页器
    total: { default: 0, type: Number }, // 总条数
    pagerCount: { default: 5, type: Number }, // 页码按钮的数量，当总页数超过该值时会折叠
    pageSize: { default: 10, type: Number }, // 每页条数
    currentPage: { default: 1, type: Number }, // 当前页
    pageSizes: { default: () => [10, 20, 30, 50], type: Array }, // 每页显示个数选择器的选项设置
    layout: { default: 'total, sizes, prev, pager, next, jumper', type: String }, // 分页组件布局，子组件名用逗号分隔
    loading: { default: false, type: Boolean }, // 表格loading效果
    isMultiCol: { default: false, type: Boolean }, // 是否开启级联
    showSummary: { default: false, type: Boolean } // 是否显示汇总
  },
  data() {
    const dropCol = this.columns;
    return {
      dropCol,
      tablePageSize: 10, // 每页条数
      tableCurrentPage: 1// 当前页
    };
  },
  inject: ['getTableHeight'],
  computed: {
    // 超出隐藏，省略号显示
    isEllipsis() {
      return function (val) {
        return this.overflowProp.includes(val);
      };
    },
    tableHeight() {
      return this.getTableHeight() - 50;
    }
  },
  watch: {
    currentPage: {
      immediate: true,
      deep: true,
      handler(val) {
        this.tableCurrentPage = val;
      }
    },
    pageSize: {
      immediate: true,
      deep: true,
      handler(val) {
        this.tablePageSize = val;
      }
    }
  },
  mounted() {
    // 阻止默认行为
    if (this.needDrag) {
      document.body.ondrop = function (event) {
        event.preventDefault();
        event.stopPropagation();
      };
      this.rowDrop();
      this.columnDrop();
    }
    this.init();
  },

  methods: {
    ...mapActions({ 'getFormulaList': 'diclist/getFormulaList' }),
    init() {
      this.getFormulaList();
    },
    // 添加类名
    addOne({ row, columnIndex }) {
      // console.log(row, columnIndex);
      if (columnIndex !== 0) {
        return 'drag';
      }
    },
    renderHeader(h, { column }) {
      // console.log(column);
      if (column.level === 1 && (column.label.trim() !== '行标签' && column.label.trim() !== '月份' && column.label.trim() !== '未完成大区数据' && column.label.trim() !== '状态' && column.label.trim() !== '操作')) {
        return h('div', [
          h('span', column.label),
          h(promptMessage, {
            props: { messages: column.label }
          })
        ]);
      }
      return h('span', column.label);
    },
    // // 行拖拽
    rowDrop() {
      const tbody = document.querySelector('.el-table__body-wrapper tbody'); // 获取table列表
      const _this = this;
      Sortable.create(tbody, {
        onEnd({ newIndex, oldIndex }) {
          const currRow = _this.data.splice(oldIndex, 1)[0];
          _this.data.splice(newIndex, 0, currRow);
        }
      });
    },
    // 列拖拽
    columnDrop() {
      const wrapperTr = document.querySelector('.el-table__header-wrapper tr');
      this.sortable = Sortable.create(wrapperTr, {
        animation: 1000,
        delay: 30,
        draggable: '.drag',
        handle: '.drag',
        onEnd: evt => {
          const oldItem = this.dropCol[evt.oldIndex];
          this.dropCol.splice(evt.oldIndex, 1);
          this.dropCol.splice(evt.newIndex, 0, oldItem);
        }
      });
    },
    tableRowClassName({ row, rowIndex }) {
      let selectedClassName = '';
      const { id = '' } = row;
      if (id && this.selectiedRows.includes(id)) {
        selectedClassName = 'success-row';
      }
      return selectedClassName;
    },
    handleCurrentChange(current) {
      this.$emit('handlePaginationChange', {
        current,
        size: this.tablePageSize
      });
    },
    handleSizeChange(size) {
      // 更改分页大小，重置当前页
      this.$emit('handlePaginationChange', {
        current: this.tableCurrentPage,
        size
      });
    },
    // 表格单选时：设置/取消选中项
    setCurrentRow(row) {
      this.$refs.tablePagination.setCurrentRow(row);
    },
    // 表格多选时：设置选中项
    toggleRowsSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.tablePagination.toggleRowSelection(row, true);
        });
      } else {
        this.clearSelection();
      }
    },
    toggleRowSelection(row) {
      this.$refs.tablePagination.toggleRowSelection(row, true);
    },
    // 表格多选时：清空选中项
    clearSelection() {
      this.$refs.tablePagination.clearSelection();
    },
    // 表格滚动条回到顶部
    handleTableScrollTop() {
      this.$refs.tablePagination.bodyWrapper.scrollTop = 0;
    }
  }
};
</script>
<style  lang="scss" scoped>
::v-deep .el-table__empty-block {
  height: 500px !important;
}
::v-deep .el-table__empty-text {
  position: absolute;
  left: 50%;
}
.pagination {
  float: right;
  margin: 16px 0;
}
.table-page {
  margin-top: 20px;
}
.el-table .success-row {
  background: #ecf5ff;
}
.empty-text {
  position: relative;
  height: 500px;
  text-align: left;
  line-height: 490px;
  font-size: 14px;
  margin-left: -85px;
}
.svg-container {
  display: inline-block;
  padding: 6px 5px 6px 0px;
  vertical-align: middle;
  width: 150px;
  height: 150px;
}
.empty-content {
  position: absolute;
  top: 86px;
  left: 46px;
}
</style>
